#include "openmp.h"

/**
 * 按二维高斯函数实现高斯滤波
 * @param src
 * @param dst
 * @param window
 */
void ompGaussianFilter(Mat &src, Mat &dst, Mat window) {
    int hh = (window.rows - 1) / 2;
    int hw = (window.cols - 1) / 2;
    dst = Mat::zeros(src.size(), src.type());
    //边界填充
    Mat newSrc;
    copyMakeBorder(src, newSrc, hh, hh, hw, hw, BORDER_REPLICATE);//边界复制
    //高斯滤波
    double sum[3] = {0};
#pragma omp parallel for simd num_threads(2) default(none) shared(newSrc, window, hh, hw, dst) private(sum) schedule(dynamic)
    for (int i = hh; i < newSrc.rows - hh; ++i) {
        for (int j = hw; j < newSrc.cols - hw; ++j) {
            sum[0] = 0;
            for (int r = -hh; r <= hh; ++r) {
                for (int c = -hw; c <= hw; ++c) {
                    if (newSrc.channels() == 1) {
//                        sum[0] = sum[0] + newSrc.at<uchar>(i + r, j + c) * window.at<double>(r + hh, c + hw);
                        sum[0] = sum[0] + newSrc.ptr<uchar>(i + r)[j + c] * window.ptr<double>(r + hh)[c + hw];
                    }
                }
            }

            for (int k = 0; k < newSrc.channels(); ++k) {
                if (sum[k] < 0)
                    sum[k] = 0;
                else if (sum[k] > 255)
                    sum[k] = 255;
            }
            if (newSrc.channels() == 1) {
                dst.at<uchar>(i - hh, j - hw) = static_cast<uchar>(sum[0]);
            }

        }
    }

}
